<template>
	<a-row :gutter="10">
		<a-col :xs="24" :sm="24" :md="24" :lg="4" :xl="4">
			<a-card :bordered="false" :loading="cardLoading">
				<a-tree
					v-if="treeData.length > 0"
					v-model:expandedKeys="treeDefaultExpandedKeys"
					:tree-data="treeData"
					:field-names="treeFieldNames"
					@select="treeSelect"
				>
				</a-tree>
				<a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE"/>
			</a-card>
		</a-col>
		<a-col :xs="24" :sm="24" :md="24" :lg="20" :xl="20">
			<a-card :bordered="false">
				<a-form ref="searchFormRef" name="advanced_search" :model="searchFormState"
						class="ant-advanced-search-form">
					<a-row :gutter="24">
						<a-col :span="6">
							<a-form-item label="门店（仓库）" name="stockStoreId">
								<a-tree-select
									v-model:value="searchFormState.stockStoreId"
									class="xn-wd"
									:dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
									placeholder="请选择门店（仓库）"
									allow-clear
									tree-default-expand-all
									:tree-data="storeTreeData"
									:tree-default-expanded-keys="storeTreeDefaultExpandedKeys"
									:field-names="{
										children: 'children',
										label: 'name',
										value: 'id'
									}"
								></a-tree-select>
							</a-form-item>

						</a-col>
						<a-col :span="6">
							<a-form-item label="商品" name="stockProductionSearchKey">
								<a-input v-model:value="searchFormState.stockProductionSearchKey"
										 placeholder="请输入商品名称/条码/助词码" allow-clear/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-form-item label="供应商" name="stockSupplier">
								<xn-page-select
									ref="xnstockSupplierPageSelectRef"
									v-model:value="searchFormState.stockSupplier"
									placeholder="请选择供应商"
									allow-clear
									show-search
									:page-function="stockSupplierSelector"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="6">
							<a-checkbox v-model:checked="searchFormState.isHavingByProduction" @change="changeIsTotal">汇总</a-checkbox>
							<a-checkbox v-model:checked="searchFormState.isShowZero" >显示0库存</a-checkbox>
							<a-button type="primary" @click="tableRef.refresh()">查询</a-button>
							<a-button style="margin: 0 8px" @click="reset">重置</a-button>
						</a-col>

						<a-col :span="2" v-show="searchFormState.isHavingByProduction">
							汇总选项：
						</a-col>
						<a-col :span="3" v-show="searchFormState.isHavingByProduction">
							<a-checkbox v-model:checked="searchFormState.isHavingByStore" @change="showStore">按门店汇总</a-checkbox>
						</a-col>
						<a-col :span="3" v-show="searchFormState.isHavingByProduction">
							<a-checkbox v-model:checked="searchFormState.isHavingByStorage" @change="showStorage">按仓库汇总</a-checkbox>
						</a-col>
						<a-col :span="3" v-show="searchFormState.isHavingByProduction">
							<a-checkbox v-model:checked="searchFormState.isHavingByStoreLocation" @change="showStoreLocation">按库位汇总</a-checkbox>
						</a-col>
						<a-col :span="3" v-show="searchFormState.isHavingByProduction">
							<a-checkbox v-model:checked="searchFormState.isHavingByProductionBatch" @change="showBatch">按批次汇总</a-checkbox>
						</a-col>
						<a-col :span="3" v-show="searchFormState.isHavingByProduction">
							<a-checkbox v-model:checked="searchFormState.isHavingByDateManufacture" @change="showDateManufacture">按生产日期汇总</a-checkbox>
						</a-col>
						<a-col :span="3" v-show="searchFormState.isHavingByProduction">
							<a-checkbox v-model:checked="searchFormState.isHavingBySupplier" @change="showSupplier">按供应商汇总</a-checkbox>
						</a-col>

					</a-row>
				</a-form>
				<s-table
					ref="tableRef"
					:columns="columns"
					:data="loadData"
					:alert="options.alert.show"
					bordered
					:row-key="(record) => record.id"
					:tool-config="toolConfig"
					:row-selection="options.rowSelection"
				>
					<template #operator class="table-operator">
						<a-space>
							<a-button @click="exportBatchStock" v-if="hasPerm('supplierWarehouseStocksExport')">
								<template #icon>
									<export-outlined/>
								</template>
								批量导出
							</a-button>
						</a-space>
					</template>
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'stockDateManufacture'">
							{{$TOOL.parseTime(record.stockDateManufacture, '{y}-{m}-{d}')}}
						</template>
						<template v-if="column.dataIndex === 'action'">
							<a-space>

							</a-space>
						</template>
					</template>
				</s-table>
			</a-card>
		</a-col>
	</a-row>
	<Form ref="formRef" @successful="tableRef.refresh()"/>
</template>

<script setup name="supplierWarehouseStocks">
import {cloneDeep} from 'lodash-es'
import Form from './form.vue'
import { onMounted} from "vue";
import supplierStocksApi from '@/api/supplier/warehouse/supplierStocksApi'
import supplierStoresApi from "@/api/supplier/base/supplierStoresApi";
import supplierStoragseApi from "@/api/supplier/warehouse/supplierStoragesApi";
import supplierSuppliersApi from "@/api/supplier/purchase/supplierSuppliersApi";
import {Empty} from "ant-design-vue";
import supplierCategoriesApi from "@/api/supplier/base/supplierCategoriesApi";
import downloadUtil from '@/utils/downloadUtil'
import sysColumnsSettingApi from "@/api/sys/setting/sysColumnsSettingApi";
import {searchStore} from "@/store";
import supplierObjectsApi from "@/api/supplier/custom/supplierObjectsApi";

const searchFormState = ref({})
const searchFormRef = ref()
const tableRef = ref()
const formRef = ref()
const toolConfig = {refresh: true, height: true, columnSetting: false, striped: false}

const treeData = ref([])
// 替换treeNode 中 title,key,children
const treeFieldNames = { children: 'children', title: 'name', key: 'id' }
const treeDefaultExpandedKeys = ref([])
const cardLoading = ref(true)

const changeIsTotal = () => {
	searchFormState.value.isHavingByStore = false
	searchFormState.value.isHavingByStorage = false
	searchFormState.value.isHavingByStoreLocation = false
	searchFormState.value.isHavingByProductionBatch = false
	searchFormState.value.isHavingByDateManufacture = false
	searchFormState.value.isHavingBySupplier = false
	const newColumns = cloneDeep(columns.value)
	newColumns.forEach(column => {
		if(column.dataIndex === 'stockBatch' || column.dataIndex === 'stockDateManufacture' || column.dataIndex === 'stockStoreIdName' || column.dataIndex === 'stockStorageIdName' || column.dataIndex === 'stockStoreLocationName' || column.dataIndex === 'stockSupplierName' || column.dataIndex === 'stockPriceProcureLast'){
			column.checked = !searchFormState.value.isHavingByProduction
		}
	})
	columns.value = newColumns
	tableRef.value.refresh(true)
}

//勾选或取消按门店汇总选项
const showStore = () =>{
	const newColumns = cloneDeep(columns.value)
	newColumns.forEach(column => {
		if(column.dataIndex === 'stockStoreIdName'){
			column.checked = searchFormState.value.isHavingByStore
		}
	})
	columns.value = newColumns
	tableRef.value.refresh()
}
//勾选或取消按仓库总选项
const showStorage = () =>{
	const newColumns = cloneDeep(columns.value)
	newColumns.forEach(column => {
		if(column.dataIndex === 'stockStorageIdName'){
			column.checked = searchFormState.value.isHavingByStorage
		}
	})
	columns.value = newColumns
	tableRef.value.refresh()
}
//勾选或取消按库位汇总选项
const showStoreLocation = () =>{
	const newColumns = cloneDeep(columns.value)
	newColumns.forEach(column => {
		if(column.dataIndex === 'stockStoreLocationName'){
			column.checked = searchFormState.value.isHavingByStoreLocation
		}
	})
	columns.value = newColumns
	tableRef.value.refresh()
}
//勾选或取消按批次汇总选项
const showBatch = () =>{
	const newColumns = cloneDeep(columns.value)
	newColumns.forEach(column => {
		if(column.dataIndex === 'stockBatch'){
			column.checked = searchFormState.value.isHavingByProductionBatch
		}
	})
	columns.value = newColumns
	tableRef.value.refresh()
}
//勾选或取消按生产日期汇总选项
const showDateManufacture = () =>{
	const newColumns = cloneDeep(columns.value)
	newColumns.forEach(column => {
		if(column.dataIndex === 'stockDateManufacture'){
			column.checked = searchFormState.value.isHavingByDateManufacture
		}
	})
	columns.value = newColumns
	tableRef.value.refresh()
}
//勾选或取消按供应商汇总选项
const showSupplier = () =>{
	const newColumns = cloneDeep(columns.value)
	newColumns.forEach(column => {
		if(column.dataIndex === 'stockSupplierName'){
			column.checked = searchFormState.value.isHavingBySupplier
		}
	})
	columns.value = newColumns
	tableRef.value.refresh()
}


const storeTreeData = ref([])

const storeTreeDefaultExpandedKeys = ref([])
// 点击树查询
const treeSelect = (selectedKeys) => {
	if (selectedKeys.length > 0) {
		searchFormState.value.stockProductionCategories = selectedKeys.toString()
	} else {
		delete searchFormState.value.stockProductionCategories
	}
	tableRef.value.refresh(true)
}
nextTick(() => {
	// 分类选择器数据
	supplierCategoriesApi.categoriesTreeSelector().then((res) => {
		if (res !== null) {
			// treeData.value = res
			cardLoading.value = false
			treeData.value = [
				{
					id: '',
					parentId: '0',
					name: '全部分类',
					children: res
				}
			]
			// 默认展开2级
			treeData.value.forEach((item) => {
				// 因为0的顶级
				if (item.parentId === '0') {
					treeDefaultExpandedKeys.value.push(item.id)
					// 取到下级ID
					if (item.children) {
						item.children.forEach((items) => {
							treeDefaultExpandedKeys.value.push(items.id)
						})
					}
				}
			})
		}
	}).finally(() => {
		cardLoading.value = false
	})
})
const columns = ref([
	{
		title: '商品编码',
		dataIndex: 'stockProductionCode'
	},
	{
		title: '主条码',
		dataIndex: 'stockProductionBarcode'
	},
	{
		title: '商品名称',
		dataIndex: 'stockProductionName'
	},
	{
		title: '规格',
		dataIndex: 'stockProductionSpec'
	},
	{
		title: '单位',
		dataIndex: 'stockProductionUnit'
	},
	{
		title: '商品库存',
		dataIndex: 'stockStock'
	},
	{
		title: '采购成本',
		dataIndex: 'stockPriceProcure'
	},
	{
		title: '最近采购价',
		dataIndex: 'stockPriceProcureLast'
	},
	{
		title: '库存金额',
		dataIndex: 'stockAmount'
	},
	{
		title: '批次',
		dataIndex: 'stockBatch'
	},
	{
		title: '生产日期',
		dataIndex: 'stockDateManufacture'
	},
	{
		title: '门店',
		dataIndex: 'stockStoreIdName'
	},
	{
		title: '仓库',
		dataIndex: 'stockStorageIdName'
	},
	{
		title: '库位',
		dataIndex: 'stockStoreLocationName'
	},
	{
		title: '供应商',
		dataIndex: 'stockSupplierName'
	},
])

const selectedRowKeys = ref([])
// 列表选择配置
const options = {
	// columns数字类型字段加入 needTotal: true 可以勾选自动算账
	alert: {
		show: false,
		clear: () => {
			selectedRowKeys.value = ref([])
		}
	},
	rowSelection: {
		onChange: (selectedRowKey, selectedRows) => {
			selectedRowKeys.value = selectedRowKey
		}
	}
}
const loadData = (parameter) => {
	const searchFormParam = cloneDeep(searchFormState.value)
	return supplierStocksApi.supplierStocksPage(Object.assign(parameter, searchFormParam)).then((data) => {
		return data
	})
}
// 重置
const reset = () => {
	searchFormRef.value.resetFields()
	searchFormState.value.isHavingByStore = false
	searchFormState.value.isHavingByStorage = false
	searchFormState.value.isHavingByStoreLocation = false
	searchFormState.value.isHavingByProductionBatch = false
	searchFormState.value.isHavingByDateManufacture = false
	searchFormState.value.isHavingBySupplier = false

	const newColumns = cloneDeep(columns.value)
	newColumns.forEach(column => {
		if(column.dataIndex === 'stockBatch' || column.dataIndex === 'stockDateManufacture' || column.dataIndex === 'stockStoreIdName' || column.dataIndex === 'stockStorageIdName' || column.dataIndex === 'stockStoreLocationName' || column.dataIndex === 'stockSupplierName'){
			column.checked = false
		}
	})
	columns.value = newColumns
	tableRef.value.refresh(true)
}


const xnstockSupplierPageSelectRef = ref();
const stockSupplierSelector = (param) => {
	return supplierObjectsApi.supplierObjectsPage(Object.assign(param, {objectType:"0"})).then((data) => {
		if (data.records){
			data.records = data.records.map((item) => {
				return {
					name: item.objectName,
					id: item.id,
				};
			});
		}
		return Promise.resolve(data)
	})
}
nextTick(() => {
	xnstockSupplierPageSelectRef.value.onPage({current: 1});
});
// 批量导出
const exportBatchStock = () => {
	if (selectedRowKeys.value.length > 0 && !searchFormState.value.isHavingByProduction) {//只有当非汇总模式下才可导出选中的行
		const params = {
			isHavingByProduction: searchFormState.value.isHavingByProduction,
			ids: selectedRowKeys.value
				.map((m) => {
					return m
				})
				.join()
		}
		supplierStocksApi.supplierStocksExport(params).then((res)=>{
			downloadUtil.resultDownload(res)
			tableRef.value.clearSelected()
		})
		return
	}
	supplierStocksApi.supplierStocksExport(searchFormState.value).then((res)=>{
		downloadUtil.resultDownload(res)
		tableRef.value.clearSelected()
	})

}
nextTick(() => {
	supplierStoresApi.supplierStoresTree().then((res) => {
		if (res !== null) {
			cardLoading.value = false
			storeTreeData.value = [
				{
					id: '',
					parentId: '0',
					name: '全部门店',
					children: res
				}
			]
			// 默认展开2级
			storeTreeData.value.forEach((item) => {
				// 因为0的顶级
				if (item.parentId === '0') {
					storeTreeDefaultExpandedKeys.value.push(item.id)
					// 取到下级ID
					if (item.children) {
						item.children.forEach((items) => {
							storeTreeDefaultExpandedKeys.value.push(items.id)
						})
					}
				}
			})
		}
	}).finally(() => {
		cardLoading.value = false
	})
})
</script>
